<template>
  <div class="myPaginate">
    <div @click="prec">上一页</div>
    <div
      v-for="item in pagess"
      :key="item"
      :class="{ active: modelValue == item }"
      @click="currentPageChange(item)"
    >
      {{ item }}
    </div>
    <div @click="next">下一页</div>
  </div>
</template>
<script>
import { ref, reactive, toRefs, computed, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
export default {
  props: {
    pages: {
      type: Number,
      default: 1,
    },
    modelValue: {
      type: Number,
      default: 1,
    },
  },
  name: "myPaginate",
  setup(props, ctx) {
    /* 定义仓库 */
    const store = useStore();
    /* 定义路由传参 */
    const router = useRouter();
    /* 定义路由收参 */
    const route = useRoute();
    /* 定义总数据存放地址 */
    const data = reactive({
      currentPage: 1,
      pagess: computed(() => {
        if (props.modelValue <= 4) {
          return [1, 2, 3, 4, 5, 6, "···"];
        } else if (props.modelValue >= props.pages - 3) {
          return [
            "···",
            props.pages - 4,
            props.pages - 3,
            props.pages - 2,
            props.pages - 1,
            props.pages,
          ];
        } else {
          return [
            "···",
            props.modelValue - 2,
            props.modelValue - 1,
            props.modelValue,
            props.modelValue + 1,
            props.modelValue + 2,
            "···",
          ];
        }
        // return props.pages;
      }),
      /* 点击页码 */
      currentPageChange: (item) => {
        // console.log(typeof item);
        if (typeof item != "number") {
          return false;
        }
        data.currentPage = item;
        ctx.emit("update:modelValue", data.currentPage);
      },
      /* 点击上一页 */
      prec: () => {
        data.currentPage = props.modelValue;
        data.currentPage--;
        if (data.currentPage <= 1) data.currentPage = 1;
        ctx.emit("update:modelValue", data.currentPage);
      },
      /* 点击下一页 */
      next: () => {
        data.currentPage = props.modelValue;
        data.currentPage++;
        if (data.currentPage >= props.pages) data.currentPage = props.pages;
        ctx.emit("update:modelValue", data.currentPage);
      },
    });
    /* 监听变化 */
    watch(
      () => data.currentPage,
      (n, o) => {
        console.log(n);
        ctx.emit("currentPageChange", n);
      }
    );
    return { ...toRefs(data) };
  },
  components: {},
};
</script>
<style lang="scss" scoped>
/* 如果不想样式污染  就加个scoped */
.myPaginate {
  display: flex;
  justify-content: center;
  padding: 30px;
  div {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      cursor: pointer;
      color: var(--color);
    }
    &.active {
      background-color: var(--color);
      color: #fff;
    }
  }
}
</style>